import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useUser } from '@contexts/UserContext';
import Tooltip from '@components/Tooltip';
import logo from '@assets/logo.png';
import aiAgent1 from '@assets/ai agent1.png';
import './styles.scss';

/**
 * 侧边栏组件
 * @returns {JSX.Element} 侧边栏组件
 */
const Sidebar = ({ conversationTitle }) => {
    const [isCollapsed, setIsCollapsed] = useState(false);
    const [hoveredItem, setHoveredItem] = useState(null);
    const [showDropdown, setShowDropdown] = useState(false);
    const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0 });
    const [dropdownTrigger, setDropdownTrigger] = useState(null);
    const navigate = useNavigate();
    const location = useLocation();
    const { user } = useUser();

    useEffect(() => {
        // console.log('User context:', user);
        const handleResize = () => {
            if (window.innerWidth <= 1200) {
                setIsCollapsed(true);
            } else {
                setIsCollapsed(false);
            }
        };

        handleResize();
        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, [user]);

    useEffect(() => {
        const handleClickOutside = (event) => {
            if (showDropdown &&
                !event.target.closest('.more-menu') &&
                !event.target.closest('.more-icon')) {
                setShowDropdown(false);
            }
        };

        document.addEventListener('click', handleClickOutside);
        return () => document.removeEventListener('click', handleClickOutside);
    }, [showDropdown]);

    const handleMoreClick = (e, trigger) => {
        e.stopPropagation();
        if (trigger === 'chat') {
            const rect = e.currentTarget.getBoundingClientRect();
            setDropdownPosition({
                top: rect.bottom + 4,
                left: rect.right - 160,
            });
            setDropdownTrigger(trigger);
            setShowDropdown(!showDropdown);
        }
    };

    const handleProfileClick = () => {
        navigate('/profile');
    };

    const navItems = [
        { icon: aiAgent1, text: "财务制度", isImage: true, path: "/financial" },
        { icon: aiAgent1, text: "智能问数", isImage: true, path: "/data-query" },
    ];

    return (
        <div className={`sidebar ${isCollapsed ? 'collapsed' : ''}`}>
            <div className="TopSection">
                <div className={`logo ${isCollapsed ? 'collapsed' : ''}`}>
                    <div className={`logo-wrapper ${isCollapsed ? 'collapsed' : ''}`}>
                        <div className="logo-content">
                            <img src={logo} alt="Logo" className="logo-image" />
                            {!isCollapsed && <span className="logo-text">AI Agent</span>}
                        </div>
                        {!isCollapsed && (
                            <button
                                className={`collapse-button ${isCollapsed ? 'collapsed' : ''}`}
                                onClick={() => setIsCollapsed(!isCollapsed)}
                                title="收起侧边栏"
                            >
                                <i className="ri-expand-left-line" />
                            </button>
                        )}
                    </div>
                    {isCollapsed && (
                        <button
                            className={`collapse-button ${isCollapsed ? 'collapsed' : ''}`}
                            onClick={() => setIsCollapsed(!isCollapsed)}
                            title="展开侧边栏"
                        >
                            <i className="ri-expand-left-line" />
                        </button>
                    )}
                </div>

                <Tooltip content="创建新对话" show={isCollapsed && hoveredItem === 'newChat'}>
                    <button
                        className={`new-chat-button ${isCollapsed ? 'collapsed' : ''}`}
                        onMouseEnter={() => setHoveredItem('newChat')}
                        onMouseLeave={() => setHoveredItem(null)}
                    >
                        <i className="ri-add-line" />
                        {!isCollapsed && <span>创建新对话</span>}
                    </button>
                </Tooltip>

                <div className="nav-section">
                    <div className={`nav-header ${isCollapsed ? 'collapsed' : ''}`}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <i className="ri-apps-2-ai-line" />
                            {!isCollapsed && <span>智能体</span>}
                        </div>
                    </div>
                    <div className="nav-items">
                        {navItems.map((item) => (
                            <Tooltip key={item.text} content={item.text} show={isCollapsed && hoveredItem === item.text}>
                                <div
                                    className={`nav-item ${isCollapsed ? 'collapsed' : ''} ${location.pathname === item.path ? 'active' : ''}`}
                                    onMouseEnter={() => setHoveredItem(item.text)}
                                    onMouseLeave={() => setHoveredItem(null)}
                                    onClick={() => item.path && navigate(item.path)}
                                >
                                    {item.isImage ? (
                                        <img src={item.icon} alt={item.text} className="nav-icon" />
                                    ) : (
                                        <i className={item.icon} />
                                    )}
                                    {!isCollapsed && <span>{item.text}</span>}
                                </div>
                            </Tooltip>
                        ))}
                    </div>
                </div>

                <div className={`divider ${isCollapsed ? 'collapsed' : ''}`} />

                <div className={`recent-chats ${isCollapsed ? 'collapsed' : ''}`}>
                    <div className={`recent-chats-header ${isCollapsed ? 'collapsed' : ''}`}>
                        <div className="recent-header-content">
                            <i className="ri-chat-ai-line" />
                            {!isCollapsed && <span>最近对话</span>}
                        </div>
                        {!isCollapsed && (
                            <div
                                className="more-menu"
                                onClick={(e) => handleMoreClick(e, 'more')}
                            >
                                <span>更多</span>
                                <i
                                    className="ri-arrow-right-s-line"
                                    style={{
                                        transform: showDropdown && dropdownTrigger === 'more' ? 'rotate(90deg)' : 'rotate(0)'
                                    }}
                                />
                            </div>
                        )}
                    </div>

                    <div className="chat-items">
                        <Tooltip content={conversationTitle || '新对话'} show={isCollapsed && hoveredItem === 'recentChat'}>
                            <div
                                className={`chat-item ${isCollapsed ? 'collapsed' : ''} ${location.pathname === '/' ? 'active' : ''}`}
                                onMouseEnter={() => setHoveredItem('recentChat')}
                                onMouseLeave={() => setHoveredItem(null)}
                                onClick={() => navigate('/')}
                            >
                                <div className="chat-dot" />
                                {!isCollapsed && <span className="chat-text">{conversationTitle || '新对话'}</span>}
                                {!isCollapsed && (
                                    <i
                                        className="ri-more-line more-icon"
                                        onClick={(e) => handleMoreClick(e, 'chat')}
                                    />
                                )}
                            </div>
                        </Tooltip>
                    </div>
                </div>
            </div>

            <Tooltip content="个人信息" show={isCollapsed && hoveredItem === 'userProfile'}>
                <div
                    className="user-profile"
                    onMouseEnter={() => setHoveredItem('userProfile')}
                    onMouseLeave={() => setHoveredItem(null)}
                    onClick={handleProfileClick}
                >
                    <img src={user?.avatarUrl} alt="User avatar" className="avatar" />
                    {!isCollapsed && <span>{user?.name || '未登录'}</span>}
                </div>
            </Tooltip>

            {showDropdown && (
                <div
                    className="dropdown"
                    style={{
                        position: 'fixed',
                        top: `${dropdownPosition.top}px`,
                        left: `${dropdownPosition.left}px`
                    }}
                    onClick={(e) => e.stopPropagation()}
                >
                    <div className="dropdown-item">
                        <i className="ri-share-line" />
                        分享
                    </div>
                    <div className="dropdown-item">
                        <i className="ri-edit-line" />
                        重命名
                    </div>
                    <div className="dropdown-item">
                        <i className="ri-star-line" />
                        收藏
                    </div>
                    <div className="dropdown-item danger">
                        <i className="ri-delete-bin-line" />
                        删除
                    </div>
                </div>
            )}
        </div>
    );
};

export default Sidebar; 